import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

#使用以下三阶多项式来生成训练和测试数据的标签：

max_degree = 20#多项式的最大阶数
n_train, n_test = 100, 100#训练和测试数据集大小
true_w = np.zeros(max_degree)#长度为20的行向量
true_w[0:4] = np.array([5, 1.2, -3.4, 5.6])#只给前四个赋值

features = np.random.normal(size=(n_train + n_test, 1))#从正态（高斯）分布中抽取随机样本
np.random.shuffle(features)#打乱下标
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))#np.power()用于数组元素求n次方。https://blog.csdn.net/qq_36512295/article/details/98472358
#poly_features为200*20
#np.arange()函数返回一个有终点和起点的固定步长的排列，如[1,2,3,4,5]，起点是1，终点是6，步长为1。
'''numpy中reshape函数的三种常见相关用法
reshape(1,-1)转化成1行：
reshape(2,-1)转换成两行：
reshape(-1,1)转换成1列：
reshape(-1,2)转化成两列'''
for i in range(max_degree):#同样，存储在poly_features中的单项式由gamma函数重新缩放
    poly_features[:, i] /= math.gamma(i + 1)# i次方的特征除以(i+1)阶乘
#用伽马函数算阶乘 gamma(i+1)=i!
labels = np.dot(poly_features, true_w)#点积
labels += np.random.normal(scale=0.1, size=labels.shape)#正态分布初始化

#看一下前2个样本
true_w, features, poly_features, labels = [#更改dtype
    torch.tensor(x, dtype=torch.float32)
    for x in [true_w, features, poly_features, labels]]

print(features[:2], poly_features[:2, :], labels[:2])

#实现一个函数来评估模型在给定数据集上的损失
def evaluate_loss(net, data_iter, loss):
    """评估给定数据集上模型的损失。"""
    metric = d2l.Accumulator(2)#损失的总和，样本数量
    for X, y in data_iter:
        out = net(X)
        y = y.reshape(out.shape)
        l = loss(out, y)
        metric.add(l.sum(), l.numel())
    return metric[0] / metric[1]
#定义训练函数
def train(train_features, test_features, train_labels, test_labels,
          num_epochs=400):
    loss = nn.MSELoss()#均方误差
    input_shape = train_features.shape[-1]
    net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
    batch_size = min(10, train_labels.shape[0])
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1, 1)),
                                batch_size)
    test_iter = d2l.load_array((test_features, test_labels.reshape(-1, 1)),
                               batch_size, is_train=False)
    trainer = torch.optim.SGD(net.parameters(), lr=0.01)
    animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
                            xlim=[1, num_epochs], ylim=[1e-3, 1e2],
                            legend=['train', 'test'])
    for epoch in range(num_epochs):
        d2l.train_epoch_ch3(net, train_iter, loss, trainer)
        if epoch == 0 or (epoch + 1) % 20 == 0:
            animator.add(epoch + 1, (evaluate_loss(
                net, train_iter, loss), evaluate_loss(net, test_iter, loss)))
    print('weight:', net[0].weight.data.numpy())#输出权重w

#三阶多项式函数拟合(正态)
train(poly_features[:n_train, :4], poly_features[n_train:, :4],#选前四列
      labels[:n_train], labels[n_train:])

#线性函数拟合(欠拟合)
train(poly_features[:n_train, :2], poly_features[n_train:, :2],#选前两列
      labels[:n_train], labels[n_train:])

#高阶多项式函数拟合(过拟合)
train(poly_features[:n_train, :], poly_features[n_train:, :],#选全部列
      labels[:n_train], labels[n_train:], num_epochs=1500)

